import tkinter as tk
from tkinter import ttk, messagebox
from typing import List, Dict, Optional, Tuple
from database import DatabaseManager
import os
import sys


class SortEmployeesWindow:
    legal_fields = [
        "employee_id", "name", "age", "gender",
        "education", "salary", "address", "phone"
    ]

    def __init__(self, parent_window, view_window, db_manager, icon_path="asset/OIP-C.ico"):
        self.parent_window = parent_window
        self.view_window = view_window
        self.db = db_manager
        self.icon_path = icon_path

        # 创建排序窗口
        self.top = tk.Toplevel(self.parent_window)
        self.top.title("职工信息排序")
        self.top.geometry("600x100")
        self.top.protocol("WM_DELETE_WINDOW", self.on_close)

        # 设置窗口图标
        self._set_window_icon()

        # 创建界面组件
        self.create_sort_frame()
        self.create_action_frame()

    def _set_window_icon(self):
        """设置窗口图标"""
        if not self.icon_path:
            return

        try:
            if sys.platform == "win32":
                self.top.iconbitmap(self.icon_path)
            else:
                img = tk.PhotoImage(file=self.icon_path)
                self.top.call('wm', 'iconphoto', self.top._w, img)
        except Exception as e:
            messagebox.showwarning("图标加载失败",
                                   f"图标加载失败：{os.path.basename(self.icon_path)}\n"
                                   f"错误详情：{str(e)}\n"
                                   f"当前路径：{os.path.abspath(self.icon_path)}")

    def create_sort_frame(self):
        """ 创建动态排序条件输入区域 """
        sort_frame = ttk.LabelFrame(self.top, text="排序条件", padding=10)
        sort_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)

        # 初始空条件
        self.condition_frames = []
        self.add_sort_condition()

    def add_sort_condition(self, event=None):
        """ 添加新的排序条件行 """
        frame = ttk.Frame(self.top)

        # 字段选择
        ttk.Label(frame, text="排序字段：").pack(side=tk.LEFT, padx=5)
        combo = ttk.Combobox(
            frame,
            values=self.legal_fields,
            state="readonly",
            width=15
        )
        combo.pack(side=tk.LEFT, padx=5)

        # 排序方式
        ttk.Label(frame, text="排序方式：").pack(side=tk.LEFT, padx=5)
        var = tk.StringVar(value="ASC")
        ttk.Radiobutton(
            frame,
            text="升序",
            variable=var,
            value="ASC"
        ).pack(side=tk.LEFT, padx=5)
        ttk.Radiobutton(
            frame,
            text="降序",
            variable=var,
            value="DESC"
        ).pack(side=tk.LEFT, padx=5)

        # 删除按钮
        def remove_condition():
            frame.destroy()
            self.condition_frames.remove(frame)

        ttk.Button(
            frame,
            text="×",
            command=remove_condition,
            width=2
        ).pack(side=tk.LEFT, padx=5)

        # 存储组件引用
        frame.combo = combo
        frame.var = var
        frame.pack(fill=tk.X, pady=2)
        self.condition_frames.append(frame)

    def create_action_frame(self):
        """ 创建操作按钮区域 """
        action_frame = ttk.Frame(self.top)
        action_frame.pack(fill=tk.X, padx=10, pady=5)

        # 添加条件按钮
        ttk.Button(
            action_frame,
            text="添加条件",
            command=self.add_sort_condition
        ).pack(side=tk.LEFT, padx=5)

        # 执行排序按钮
        ttk.Button(
            action_frame,
            text="执行排序",
            command=self.execute_sort
        ).pack(side=tk.RIGHT, padx=5)

    def build_order_clause(self) -> Tuple[str, tuple]:
        """ 构建ORDER BY子句 """
        order_clauses = []
        params = []

        for frame in self.condition_frames:
            field = frame.combo.get()
            order = frame.var.get()

            if not field:
                continue

            if field not in self.legal_fields:
                messagebox.showwarning(
                    "非法字段",
                    f"'{field}' 不是有效的排序字段"
                )
                return "", ()

            order_clauses.append(f"{field} {order}")

        order_clause = "ORDER BY " + ", ".join(order_clauses) if order_clauses else ""
        return order_clause, ()

    def execute_sort(self):
        """ 执行排序查询并刷新父窗口 """
        order_clause, params = self.build_order_clause()

        try:
            # 构建完整查询
            base_query = "SELECT * FROM employee"
            full_query = f"{base_query} {order_clause}"

            # 执行查询
            data = self.db.execute_query(full_query, params, fetch_all=True) or []

            if self.view_window and hasattr(self.view_window, 'update_treeview'):
                self.view_window.update_treeview(data)
                self.view_window.current_page = 1
                self.view_window.load_data()
                messagebox.showinfo("成功", "排序完成并已刷新数据")
            else:
                messagebox.showwarning("警告", "未找到可刷新的数据窗口")

        except Exception as e:
            messagebox.showerror("排序失败", f"错误信息: {str(e)}")

    def on_close(self):
        """ 窗口关闭处理 """
        self.top.destroy()
